package dml.users.proc;

import dml.users.aggr.KeepAliveSession;
import dml.users.aggr.Session;
import dml.users.aggr.UserLoginState;
import dml.users.repo.SessionRepository;
import dml.users.repo.UserLoginStateRepository;

public class KeepAliveSessionProcesses {

    private SessionRepository<Session> sessionRepository;

    private UserLoginStateRepository<UserLoginState, Object> userLoginStateRepository;

    public KeepAliveSessionProcesses(SessionRepository<?> sessionRepository,
                                     UserLoginStateRepository<?, ?> userLoginStateRepository) {
        this.sessionRepository = (SessionRepository<Session>) sessionRepository;
        this.userLoginStateRepository = (UserLoginStateRepository<UserLoginState, Object>) userLoginStateRepository;
    }

    public <SE extends KeepAliveSession> SE checkSessionAndActivate(
            String token, long currTime) {
        KeepAliveSession session = (KeepAliveSession) sessionRepository
                .take(token);
        if (session != null) {
            session.getKeepAlive().activate(currTime);
        }
        return (SE) session;
    }

    public <SE extends KeepAliveSession> SE checkAndRemoveOvertimeSession(
            String sessionId, long currTime) {
        KeepAliveSession session = (KeepAliveSession) sessionRepository
                .take(sessionId);
        if (session != null) {
            if (!session.getKeepAlive().checkAlive(currTime)) {
                sessionRepository.remove(sessionId);
                userLoginStateRepository.remove(session.getUserId());
                return (SE) session;
            }
        }
        return null;
    }

}
